﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace SharePointUtilitiesForDevelopers.Mapper
{
    /// <summary>
    /// A mapper that maps the xml web service response to a <see cref="SharePointListView"/>.
    /// </summary>
    public class SharePointListViewMapper : IMapper<XElement, SharePointListView>
    {
        /// <summary>
        /// Maps the source type to the target type.
        /// </summary>
        /// <param name="from">The object to map from.</param>
        /// <returns>The mapped object.</returns>
        public SharePointListView Map(XElement from)
        {
            return MapList(from).SingleOrDefault();
        }

        /// <summary>
        /// Maps the source type to a list of the target type.
        /// </summary>
        /// <param name="from">From.</param>
        /// <returns></returns>
        public IEnumerable<SharePointListView> MapList(XElement from)
        {
            try
            {
                var views = SharePointMapper.MapResponseToList<SharePointListView>(
                    MapInternal,
                    ele => string.Compare(ele.Name.LocalName, "View", StringComparison.InvariantCultureIgnoreCase) == 0,
                    from);

                return views.OrderBy(view => view.DisplayName).ToList();
            }
            catch (Exception ex)
            {
                throw new SharePointMapperException<XElement, SharePointListView>(ex);
            }
        }

        /// <summary>
        /// Maps the element to a domain object.
        /// </summary>
        /// <param name="element">The element to map from.</param>
        /// <returns>The mapped object.</returns>
        private static SharePointListView MapInternal(XElement element)
        {
            return new SharePointListView
                       {
                           Name = SharePointXml.GetAttributeAsString(element, "Name"),
                           DisplayName = SharePointXml.GetAttributeAsString(element, "DisplayName"),
                           Url = SharePointXml.GetAttributeAsString(element, "Url"),
                           ViewFieldsDefinition = SharePointXml.GetChildElement(element, "ViewFields"),
                           QueryDefinition = SharePointXml.GetChildElement(element, "Query"),
                           RowLimitDefinition = SharePointXml.GetChildElement(element, "RowLimit"),
                           RowLimit = SharePointXml.GetChildElementValueAsNullableInteger(element, "RowLimit"),
                           DefaultView = SharePointXml.GetAttributeAsBoolean(element, "DefaultView"),
                           Definition = element
                       };
        }
    }
}